package hn.sigit.view;

import hn.sigit.dao.hnd.administrative.HND_PermitRuleGroupDAO;
import hn.sigit.model.hnd.administrative.HND_PermitRuleGroup;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Name("optionsHelper")
@Scope(value=ScopeType.CONVERSATION)
@AutoCreate
public class OptionsHelper implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private List<HND_PermitRuleGroup> spatialRuleGroups;
	private List<SelectItem> spatialRuleGroupsSelectList;
	private HND_PermitRuleGroupConverter permitRuleGroupConverter;

	public List<HND_PermitRuleGroup> getSpatialRuleGroups() {
		if (spatialRuleGroups == null) {
			spatialRuleGroups = HND_PermitRuleGroupDAO.loadPermitRuleGroups();
		}
		return spatialRuleGroups;
	}

	public List<SelectItem> getSpatialRuleGroupsSelectList() {
		if (spatialRuleGroupsSelectList == null) {
			spatialRuleGroupsSelectList = new ArrayList<SelectItem>();
			spatialRuleGroupsSelectList.add(new SelectItem(null, "(seleccionar)"));
			for (HND_PermitRuleGroup prg : getSpatialRuleGroups()) {
				spatialRuleGroupsSelectList.add(new SelectItem(prg, prg.getName()));
			}
		}
		return spatialRuleGroupsSelectList;
	}

	public HND_PermitRuleGroupConverter getPermitRuleGroupConverter() {
		if (permitRuleGroupConverter == null) {
			permitRuleGroupConverter = new HND_PermitRuleGroupConverter();
		}
		return permitRuleGroupConverter;
	}



	public class HND_PermitRuleGroupConverter implements Converter {
		@Override
		public Object getAsObject(FacesContext context, UIComponent component, String value) {
			long id = Long.parseLong(value);
			
			for (HND_PermitRuleGroup prg : getSpatialRuleGroups())
				if (prg.getId() == id)
					return prg;
			
			return null;
		}

		@Override
		public String getAsString(FacesContext context, UIComponent component, Object value) {
			if (value == null) return "";
			
			return String.valueOf(((HND_PermitRuleGroup) value).getId());
		}
		
	}
}
